package com.steadyoung.modelapp.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.steadyoung.modelapp.R;
import com.steadyoung.modelapp.adapter.MyPagerAdapter;
import com.steadyoung.modelapp.base.BaseActivity;
import com.steadyoung.modelapp.entity.TabEntity;
import com.steadyoung.modelapp.fragment.DialogFragment;
import com.steadyoung.modelapp.fragment.LoadingFragment;
import com.steadyoung.modelapp.fragment.SimpleCardFragment;
import com.steadyoung.modelapp.util.common.ToastUtils;
import com.steadyoung.modelapp.util.common.Utils;

import java.util.ArrayList;
import java.util.Random;

import butterknife.BindView;
import rx.Subscription;

/**
 * Created by Administrator on 2017/9/7.
 * Email : steadyoung@foxmail.com
 * Auth  : wayne
 * Desc  : 主界面
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.main_vp)
    ViewPager main_vp;
    @BindView(R.id.main_common_tab)
    CommonTabLayout main_common_tab;

    private int[] mIconUnselectIds = {
            R.mipmap.home, R.mipmap.query, R.mipmap.track, R.mipmap.network, R.mipmap.account};
    private int[] mIconSelectIds = {
            R.mipmap.home_select, R.mipmap.query_select, R.mipmap.track_select, R.mipmap.network_select, R.mipmap.account_select};
    //    private String[] mTitles = get{getString(R.string.homepage), "我的购物车", "我的订单"};
    private String[] mTitles;

    private ArrayList<Fragment> mFragments = new ArrayList<>();

    Random mRandom = new Random();


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }


    @Override
    protected void initData() {
        mTitles = getResources().getStringArray(R.array.main_item);
        setMainViewPager();
//        loginToken();
//        PermissionUtils.requestPermissions(SelectCityPopwin.this,1,{Permission.});
    }

    @Override
    protected void initEvent() {

    }

    private void setMainViewPager() {
        for (String title : mTitles) {
            mFragments.add(SimpleCardFragment.getInstance("Switch ViewPager " + title));
        }
        mFragments.set(0,new DialogFragment());
        mFragments.set(1,new LoadingFragment());
        main_vp.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), mFragments, mTitles));

        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        main_common_tab.setTabData(mTabEntities);
        main_common_tab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                main_vp.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
//                if (position == 0) {
//                    main_common_tab.showMsg(0, mRandom.nextInt(100) + 1);
////                    UnreadMsgUtils.show(mTabLayout_2.getMsgView(0), mRandom.nextInt(100) + 1);
//                }
            }
        });

        main_vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                main_common_tab.setCurrentTab(position);
                setCenterText(mTitles[position]);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        main_vp.setCurrentItem(0);
        setCenterText(mTitles[0]);

    }

    @Override
    public void onLeftClick(View v) {
    }
/*
    *//**
     * 每次重新启动都会重新获取TOKEN
     *//*
    private void loginToken(){
        String email = SPUtils.getInstance().getString(ParamKeys.EMAIL);
        String password = SPUtils.getInstance().getString(ParamKeys.PASSWORD);
        if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)){
            HttpMethods.getInstance().userLogin(new CommonSubscriber<UserInfo>(userLoginOnNextListener), email, password);
        }
    }

    */

    /**
     * 登录网络请求返回处理
     *//*
    SubscriberOnNextListener userLoginOnNextListener = new SubscriberOnNextListener<UserInfo>() {
        @Override
        public void onNext(UserInfo userInfo) {
//            ToastUtils.showShort(R.string.login_success);
            LogUtils.d(getResources().getString(R.string.login_success) + ">>>>" + GsonUtil.toJson(userInfo));
            AppData.getInstance().setUserInfo(userInfo);
//            SPUtils.getInstance().put(ParamKeys.TOKEN,userInfo.getToken());
        }

        @Override
        public void onError(Throwable e) {

        }
    };*/
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        rxSubscription = RxBus.getDefault().toObservable(PayStatusEvent.class)
//                .subscribe(new Action1<PayStatusEvent>() {
//                               @Override
//                               public void call(PayStatusEvent userEvent) {
//                                   if(userEvent == null) return;
//                                   switch (userEvent.getOperCode()){
//                                       case ParamKeys.PAY_STATUS_SUCCESS:
//                                           main_vp.setCurrentItem(3);
//                                           break;
//                                       case ParamKeys.PAY_STATUS_FAIL_SEE_ORDER:
//                                           main_vp.setCurrentItem(3);
//                                           break;
//                                   }
//                               }
//                           },
//                        new Action1<Throwable>() {
//                            @Override
//                            public void call(Throwable throwable) {
//                                //  处理异常
//
//                            }
//                        });
    }

    Subscription rxSubscription;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rxSubscription != null) rxSubscription.unsubscribe();
    }


    //退出时的时间
    private long mExitTime;

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ToastUtils.showShort(R.string.exit_tips);
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            Utils.finishAll();
            System.exit(0);
        }
    }

}
